package com.typy.www.tpay.volley;

import android.content.Context;

import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.bean.BaseReturn2;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.ToastUtil;
import com.typy.www.tpay.util.UiHelper;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class VolleyListener implements Response.ErrorListener, Listener<String> {
    /**
     * 访问成功或者失败都会调用此方法，可以在这里做progressBar的操作或者其他
     */
    public void requestComplete() {
    }

    ;

    public abstract void onResponse(BaseReturn ret);

    public abstract void onResponseErr(int code, String msg);

    @Override
    public void onErrorResponse(VolleyError error) {

    }

    @Override
    public void onResponse(String response) {
        Logutil.print("返回值===" + response);
        JSONObject data = null;
        String datas="";
        //预防data返回值为string时闪退
        try {
            JSONObject object = new JSONObject(response);
            data = object.getJSONObject("data");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseReturn baseReturn  = GsonUtils.parseJSON(response, BaseReturn.class);
        if (data != null)
            baseReturn.setData(data);
        else{
            if(baseReturn==null){
                baseReturn=  getEreturn(response);
            }
        }
//        if (baseReturn != null && baseReturn.getCode() != Constance.SUCCESE) {
//            if(!baseReturn.getMsg().equals("红包已经领！"))
//            ToastUtil.getInstance().show(baseReturn.getMsg());
//            onResponseErr(baseReturn.getCode(), baseReturn.getMsg());
//            return;
//        }
        onResponse(baseReturn);
    }

    private BaseReturn getEreturn(String response){
        BaseReturn2 baseReturn2  = GsonUtils.parseJSON(response, BaseReturn2.class);
        BaseReturn baseReturn=new BaseReturn();
        baseReturn.setCode(baseReturn2.getCode());
        baseReturn.setMsg(baseReturn2.getMsg());
        baseReturn.setSuccess(baseReturn2.isSuccess());
        JSONObject object=new JSONObject();
        try {
            object.put("data",baseReturn2.getData());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        baseReturn.setData(object);
        return baseReturn;
    }
}
